<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/5/27
 * Time: 14:43
 */

namespace App\Models\Traits;

use Illuminate\Http\Request;



trait SearchHandler
{
    /**
     * 查询数据 条件生成 .
     * $page , 当前页
     * $limit ,每页查询多少条数据
     * $where ,返回条件集合
     * $verify ,是否有条件，没有不进行查询
     * $exclude ，特殊条件 ，拿到外面进行组合,前端 notverify：字段定义的数据都将放入此数组
     */
    public function SearchHandler(Request $request){
        $field = $request->all();

        // $excludeField 如果有不用验证的，标记为去除
        $excludeField   = $request->has('notverify') ? array_keys($field['notverify']) : [];
        $page   = $request->has('page') ? $field['page'] : 1;
        $limit  = $request->has('limit') ? $field['limit'] : 10;
        $parame = !empty($field['parame']) ? $field['parame'] : [];
        $condition = !empty($field['condition']) ? $field['condition'] : [];

        $where = [];
        $exclude = [];
        $verify = false;

        foreach ($parame as $k=>$v){
            if (in_array($k , $excludeField)){
                $exclude[$k] = $v;
                continue;
            }

            if (empty($v)){
                continue;
            }else{
                $verify = true;
            }

            $condition = !empty($condition[$k]) ? $condition[$k] : '%*%';
            switch (strtolower($condition)){
                case '=':
                    $where[] = [$k , '=' , $v];
                    break;
                case '%*%':
                    $where[] = [$k , 'LIKE' , "%{$v}%"];
                    break;
                case '*%':
                    $where[] = [$k , 'LIKE' , "{$v}%"];
                    break;
                case '%*':
                    $where[] = [$k , 'LIKE' , "%{$v}"];
                    break;
                case 'between':
                    list($t1,$t2) = explode('/' , $v);
                    $where[] = [$k , 'between' , [$t1 , $t2.' 23:59:59']];
                    break;
            }
        }

        return [$limit , $where , $verify , $exclude ,$page];
    }



    /**
     * 返回 layui 表格须要的json格式数据
     */
    public function requestLayuiData($data)
    {
        $datas['code']   = 0;
        $datas['msg']    = '';
        $datas['count']  = $data->count() ? $data->total() : 0;
        $datas['data']   = $data->count() ? $data->items() : 0;

        return $datas;
        return response()->json($datas);
    }



}